package com.sdms.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sdms.core.auth.Priviledges;
import com.sdms.core.auth.UnauthorisedUserException;
import com.sdms.core.rbac.Right;

public class DeliveryStore implements IDeliveryStore
{
	private static Map<String, DeliveryDetails> deliveryItems = new HashMap<String, DeliveryDetails>();

	private static DeliveryStore deliveryStore;

	static
	{
		DeliveryDetails item1 = new DeliveryDetails( "Jane", "Galle", "Colombo", "Mobile device" );
		DeliveryDetails item2 = new DeliveryDetails( "Smith", "Colombo", "London", "Express delivery" );
		DeliveryDetails item3 = new DeliveryDetails( "John", "Galle", "Colombo", "Electronic equipments" );
		DeliveryDetails item4 = new DeliveryDetails( "Mike", "Colombo", "Jaffna", "Gift item" );
		DeliveryDetails item5 = new DeliveryDetails( "Jane", "Colombo", "Dubai", "Food items" );
		deliveryItems.put( item1.getItemId(), item1 );
		deliveryItems.put( item2.getItemId(), item2 );
		deliveryItems.put( item3.getItemId(), item3 );
		deliveryItems.put( item4.getItemId(), item4 );
		deliveryItems.put( item5.getItemId(), item5 );
	}

	private DeliveryStore()
	{
	}

	public static synchronized DeliveryStore getInstance()
	{
		if ( deliveryStore == null )
		{
			deliveryStore = new DeliveryStore();
		}
		return deliveryStore;
	}

	@Override
	public String addItem( DeliveryDetails details ) throws UnauthorisedUserException
	{
		if ( Priviledges.retrieveCurrentPriviledges().equals( Right.R_ADD_ITEM ) )
		{
			deliveryItems.put( details.getItemId(), details );
			return details.getItemId();
		}
		String msg = "User doesn't have required priviledges to add item into store";
		throw new UnauthorisedUserException( msg );
	}

	@Override
	public DeliveryDetails removeItem( String itemId ) throws UnauthorisedUserException
	{
		if ( Priviledges.retrieveCurrentPriviledges().equals( Right.R_CANCEL_DELIVERY ) )
		{
			DeliveryDetails dd = deliveryItems.get( itemId );
			if ( dd != null )
			{
				deliveryItems.remove( itemId );
			}
			return dd;
		}
		String msg = "User doesn't have required priviledges to add item into store";
		throw new UnauthorisedUserException( msg );
	}

	@Override
	public DeliveryDetails viewDetails( String itemId ) throws UnauthorisedUserException
	{
		if ( Priviledges.retrieveCurrentPriviledges().equals( Right.R_VIEW_ITEM ) )
		{
			return deliveryItems.get( itemId );
		}
		String msg = "User doesn't have required priviledges to view item";
		throw new UnauthorisedUserException( msg );
	}

	@Override
	public List<DeliveryDetails> viewDetails() throws UnauthorisedUserException
	{
		if ( Priviledges.retrieveCurrentPriviledges().equals( Right.R_VIEW_LIST ) )
		{
			return new ArrayList<DeliveryDetails>( deliveryItems.values() );
		}
		String msg = "User doesn't have required priviledges to view item list";
		throw new UnauthorisedUserException( msg );
	}
}
